import re
import random

from utils.sendsms import Sendcode
from django.shortcuts import render
from django.contrib.auth import authenticate
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from django.core.cache import cache

from superuser.models import SuperUser


class LoginByPwd(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if not all([username, password]):
            return Response({
                'code': 400,
                'msg': '参数不全'
            })
        user = authenticate(username=username, password=password)
        if not user:
            return Response({
                'code': 400,
                'msg': '用户名或密码错误'
            })
        refresh = RefreshToken.for_user(user)
        return Response({
            'code': 200,
            'msg': '登录成功',
            'data': {
                'refresh': str(refresh),
                'token': str(refresh.access_token),
                'username': user.username,
                'id': user.id,
            }
        })


class Send(APIView):
    def post(self, request):
        # 获取手机号
        phone = request.data.get('phone')
        if not phone:
            return Response({
                'code': 400,
                'msg': '手机号不能为空'
            })
        # 验证手机号格式
        result = re.match(r'^1[3-9]\d{9}$', phone)
        if not result:
            return Response({
                'code': 400,
                'msg': '手机号格式错误'
            })
        # 判断缓存中是否存在验证码
        key = 'user:send:code' + phone
        cachecode = cache.get(key)
        # 如果缓存中存在验证码，则返回错误
        if cachecode:
            return Response({
                'code': 200,
                'msg': '验证码已发送，请勿重复发送'
            })
        # 如果缓存中不存在验证码，则生成验证码
        code = str(random.randint(1000, 9999))
        # 发送验证码
        Sendcode.send_message(phone, code)
        # 缓存验证码
        cache.set(key, code, 60 * 5)
        return Response({
            'code': 200,
            'msg': '发送成功'
        })


class Login(APIView):
    def post(self, request):
        # 获取参数
        phone = request.data.get('phone')
        code = request.data.get('code')
        # 检查参数格式
        if not phone or not code:
            return Response({
                'code': 400,
                'msg': '参数不全'
            })
        # 验证手机号格式
        result = re.match(r'^1[3-9]\d{9}$', phone)
        if not result:
            return Response({
                'code': 400,
                'msg': '手机号格式错误'
            })
        # 验证验证码
        key = 'user:send:code' + phone
        cachecode = cache.get(key)
        if cachecode != code:
            return Response({
                'code': 400,
                'msg': '验证码错误'
            })
        # 检查用户是否存在 检查手机号在数据库是否存在
        userinfo = SuperUser.objects.filter(phone=phone).first()
        # 如果不存在则创建用户
        if not userinfo:
            userinfo = SuperUser.objects.create(phone=phone, username=phone)
        # 生成token
        refresh = RefreshToken.for_user(userinfo)
        # 返回数据
        return Response({
            'code': 200,
            'msg': '登录成功',
            'data': {
                'refresh': str(refresh),
                'access': str(refresh.access_token),
                'username': userinfo.username,
                'id': userinfo.id,
            }
        })


class Register(APIView):
    def post(self, request):
        # 获取参数
        username = request.data.get('username')
        phone = request.data.get('phone')
        password = request.data.get('password')
        code = request.data.get('code')
        # 验证参数是否存在
        if not all([username, phone, password, code]):
            return Response({
                'code': 400,
                'msg': '参数不全'
            })
        # 验证用户名是否存在
        if SuperUser.objects.filter(username=username).exists():
            return Response({
                'code': 400,
                'msg': '用户名已存在'
            })
        # 验证手机号格式
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return Response({
                'code': 400,
                'msg': '手机号格式错误'
            })
        # 验证手机号是否存在
        if SuperUser.objects.filter(phone=phone).exists():
            return Response({
                'code': 400,
                'msg': '手机号已存在'
            })
        # 验证密码格式，要求密码大写字母，小写字母特殊符号
        if not re.match(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{6,20}$', password):
            return Response({
                'code': 400,
                'msg': '密码格式错误'
            })
        # 验证验证码
        key = 'user:send:code' + phone
        cachecode = cache.get(key)
        if cachecode != code:
            return Response({
                'code': 400,
                'msg': '验证码错误'
            })
        # 创建用户
        user = SuperUser.objects.create_user(username=username, phone=phone, password=password)
        # 生成token
        refresh = RefreshToken.for_user(user)
        return Response({
            'code': 200,
            'msg': '注册成功',
            'data': {
                'refresh': str(refresh),
                'access': str(refresh.access_token),
                'username': user.username,
                'id': user.id,
            }
        })